﻿using System;
using System.Text;
using System.Reflection;
using System.Data;
using System.Windows.Forms;
using System.IO;
using System.Drawing;
using Ice.Lib.Framework;
using Ice.UI.FormFunctions;
using Ice.Core;
using System.Net.Mail;
using System.Net;
using System.Diagnostics;
using Infragistics.Win.UltraWinToolbars;
using Ice.Adapters;
using System.Collections;
using Ice.Lib.Customization;
using Ice.Lib.Searches;
using Ice.BO;

namespace Epicor.Pub
{
    /// <summary>公共方法</summary>
    public class PubFun
    {
      
        #region 常用方法
        /// <summary>获取adapter数据</summary>
        public static DataTable GetAdapterData(EpiTransaction otran, string AdapterN, string whereClause = "", Boolean showSeach = false, Boolean multiSelect = true)
        {
            Boolean recSelected;
            DataSet dsAdapter = SearchFunctions.listLookup(otran, AdapterN, out recSelected, showSeach, whereClause, multiSelect);
            DataTable dt = new DataTable();
            if (recSelected)
            {
                dt = dsAdapter.Tables[0];
            }
            return dt;
        }

        /// <summary>从BAQ获取数据</summary>
        public static DataTable GetBAQData(EpiTransaction otrans, string queryID, bool clearWhere = false, BAQWhereItem[] queryWhere = null)
        {
            DataTable dt = null;
            DynamicQueryAdapter dqa = new DynamicQueryAdapter(otrans);
            try
            {
                dqa.BOConnect();
                bool bl = dqa.GetByID(queryID);

                if (bl)
                {
                    if (clearWhere) dqa.QueryDesignData.QueryWhereItem.Clear();
                    if (queryWhere != null)
                    {
                        for (int r = 0; r < queryWhere.Length; r++)
                        {
                            DynamicQueryDataSet.QueryWhereItemRow row1 = queryWhere[r].GetNewQueryWhereItemRow(dqa);
                            dqa.QueryDesignData.QueryWhereItem.Rows.Add(row1);
                        }
                    }
                    QueryExecutionDataSet qed = new QueryExecutionDataSet();
                    dqa.Execute(dqa.QueryDesignData, qed);
                    dt = dqa.QueryResults.Tables[0];
                }
            }
            catch (Exception e1)
            {

            }
            finally
            {
                dqa.Dispose();
            }
            return dt;
            //DataTable dt = null;
            //AdpAssembly adp = new AdpAssembly(otrans, "DynamicQuery");
            //try
            //{
            //    adp.BOConnect();
            //    bool bl = adp.GetByID(new object[] { queryID }, new Type[] { typeof(string) });

            //    if (bl)
            //    {
            //        DataSet ds1 = adp.GetCurrentDataSet();
            //        if (clearWhere) ds1.Tables["QueryWhereItem"].Clear();
            //        if (queryWhere != null)
            //        {
            //            for (int r = 0; r < queryWhere.Length; r++)
            //            {
            //                DataRow row1 = ds1.Tables["QueryWhereItem"].NewRow();

            //                ds1.Tables["QueryWhereItem"].Rows.Add(row1);
            //            }
            //        }
            //        QueryExecutionDataSet qed = new QueryExecutionDataSet();
            //        dqa.Execute(dqa.QueryDesignData, qed);
            //        dt = dqa.QueryResults.Tables[0];
            //    }
            //}
            //catch (Exception e1)
            //{

            //}
            //finally
            //{
            //    dqa.Dispose();
            //}
            //return dt;
        }
        /// <summary> 调用BAQ报表界面 </summary>
        public static void OpenBAQReportForm(EpiTransaction otran, string BAQReportName, KeyValue[] list)
        {
            try
            {
                LaunchFormOptions lfo = new LaunchFormOptions();
                lfo.ValueIn = BAQReportName;
                UIReflector BAQForm = ProcessCaller.LaunchCallbackForm(otran, "Ice.UIRpt.BAQReport", lfo);
                EpiDataView ParamView = (EpiDataView)BAQForm.UITrans.EpiDataViews["ReportParam"];
                if (list != null)
                {
                    ParamView.dataView[ParamView.Row].BeginEdit();
                    for (int i = 0; i < list.Length; i++)
                    {
                        ParamView.dataView[ParamView.Row][list[i].Key] = list[i].Value;//传递参数到BAQ报表
                    }
                    ParamView.dataView[ParamView.Row].EndEdit();
                }
                BAQForm.UITrans.NotifyAll();
            }
            catch (Exception e)
            {
                throw new Exception("调用BAQ报表界面错误！" + e.Message);
            }
        }

        /// <summary>打开菜单</summary>
        public static void OpenMenu(EpiTransaction otrans, string menuID, string valueIn = "")
        {
            LaunchFormOptions opts = new LaunchFormOptions();
            opts.ValueIn = valueIn;
            ProcessCaller.LaunchForm(otrans, menuID, opts);
        }

        /// <summary>根据类名打开窗体</summary>
        public static UIReflector OpenForm(EpiTransaction otrans, string assemblyName, string valueIn = "", bool suppress = false)
        {
            LaunchFormOptions opts = new LaunchFormOptions();
            opts.IsModal = suppress;
            opts.SuppressFormSearch = suppress;
            opts.ValueIn = valueIn;
            return ProcessCaller.LaunchCallbackForm(otrans, assemblyName, opts);
        }

        /// <summary>根据类名打开窗体</summary>
        public static SearchOptions GetSearchOptions(KeyValue[] kv)
        {
            Hashtable wcHash = new Hashtable();
            for(int i = 0; i < kv.Length; i++)
            {
                wcHash.Add(kv[i].Key, kv[i].Value);
            }
            SearchOptions opts = SearchOptions.CreateRuntimeSearch(wcHash, DataSetMode.RowsDataSet);
            return opts;
        }

        ///// <summary>调用系统方法显示水晶报表</summary>
        //public static void ViewCrystalReport(EpiTransaction otran,DataSet ds, string rptName, string rptTitle = null)
        //{
        //    try
        //    {
        //        if (rptTitle == null) rptTitle = rptName;
        //        if (!Directory.Exists(Application.StartupPath + @"\Temp"))
        //        {
        //            Directory.CreateDirectory(Application.StartupPath + @"\Temp");
        //        }
        //        ds.WriteXml(Application.StartupPath + @"\Temp\" + rptName + ".xml", XmlWriteMode.WriteSchema);
        //        ds.WriteXml(Application.StartupPath + @"\Temp\" + rptName + "_1.xml", XmlWriteMode.WriteSchema);
        //        //MessageBox.Show(Application.StartupPath + @"\Temp\" + rptName + ".xml");
        //        File.Copy(GetServersPath(GetServerName(otran)) + @"\reports\CustomReports\" + rptName + ".rpt", Application.StartupPath + @"\Temp\" + rptName + ".rpt", true);
        //        for (int x = 1; x <= 1000; x++)
        //        {
        //            Application.DoEvents();
        //            System.Threading.Thread.Sleep(30);
        //        }
        //        if (EpiCrystalReport.IsRequiredCrystalRuntimeInstalled())
        //        {
        //            //会删除这两个文件
        //            EpiCrystalViewer Viewer = new EpiCrystalViewer(Application.StartupPath + @"\Temp\" + rptName + ".rpt", Application.StartupPath + @"\Temp\" + rptName + ".xml", rptTitle);
        //            Viewer.Show();
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw new Exception("ViewReport错误！" + e.Message);
        //    }
        //}


        /// <summary> 初始化EpiUltraGrid字段</summary>
        public static DataTable InitEpiUltraGrid(EpiUltraGrid ug1, PubColumn[] columns, string languageID = "sch")
        {
            DataTable dt = new DataTable();
            for (int i = 0; i < columns.Length; i++)
            {
                dt.Columns.Add(columns[i].ColumnName, columns[i].ColumnType);
            }
            ug1.DataSource = dt;
            for (int i = 0; i < columns.Length; i++)
            {
                if (languageID.ToLower() == "sch")
                {
                    ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].Header.Caption = columns[i].ColumnCaptionSch;
                }
                else
                {
                    ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].Header.Caption = columns[i].ColumnCaptionEng;
                }
                ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].Width = columns[i].ColumnWidth;
                ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].Hidden = columns[i].Hidden;
                ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].CellAppearance.TextVAlign = Infragistics.Win.VAlign.Middle;
                if (!columns[i].AllowEdit)
                {
                    ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].CellActivation = Infragistics.Win.UltraWinGrid.Activation.NoEdit;
                    ug1.DisplayLayout.Bands[0].Columns[columns[i].ColumnName].CellAppearance.BackColor = Color.Gray;//Lavender'Gray'DarkGray,LightGray
                }
                if (columns[i].ColumnType == typeof(decimal))
                {
                    InitEpiUGNumber(ug1, columns[i].ColumnName, columns[i].ColumnDigits);

                }
            }
            return dt;
        }

        /// <summary> 初始化EpiUltraGrid字段下拉列表</summary>
        public static void InitEpiUltraGridDDL(EpiUltraGrid ug1, string colName, DataTable dt, string valueColName, string textColName = null, int type = 0)
        {
            if (textColName == null)
            {
                textColName = valueColName;
            }
            ug1.DisplayLayout.ValueLists.Add(colName);
            Infragistics.Win.ValueListItem[] list = new Infragistics.Win.ValueListItem[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                switch (type)
                {
                    case 1:
                        list[i] = new Infragistics.Win.ValueListItem(dt.Rows[i][valueColName],
                            Convert.ToString(dt.Rows[i][valueColName]) + "(" + Convert.ToString(dt.Rows[i][textColName]) + ")");
                        break;
                    default:
                        list[i] = new Infragistics.Win.ValueListItem(dt.Rows[i][valueColName], Convert.ToString(dt.Rows[i][textColName]));
                        break;
                } 
            }
            ug1.DisplayLayout.ValueLists[colName].ValueListItems.AddRange(list);
            ug1.DisplayLayout.ValueLists[colName].DisplayStyle = Infragistics.Win.ValueListDisplayStyle.DisplayText;
            ug1.DisplayLayout.Bands[0].Columns[colName].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDown;
            ug1.DisplayLayout.Bands[0].Columns[colName].ValueList = ug1.DisplayLayout.ValueLists[colName];
        }
        /// <summary> 初始化EpiUltraGrid数字字段</summary>
        public static void InitEpiUGNumber(EpiUltraGrid ug1, string colName, int n = 0)
        {
            string str1 = "#,###,###,##0";
            for (int i = 0; i < n; i++)
            {
                if (i == 0)
                {
                    str1 += ".";
                }
                str1 += "0";
            }
            ug1.DisplayLayout.Bands[0].Columns[colName].Format = str1;
            ug1.DisplayLayout.Bands[0].Columns[colName].CellAppearance.TextHAlign = Infragistics.Win.HAlign.Right;
        }

        /// <summary> 初始化EpiNumericEditor数据格式</summary>
        public static void InitEpiNumericEditor(EpiNumericEditor epiNE, int n = 0)
        {
            string str1 = "#,###,###,##0";
            string str2 = "-n,nnn,nnn,nnn";
            for (int i = 0; i < n; i++)
            {
                if (i == 0)
                {
                    str1 += ".";
                    str2 += ".";
                }
                str1 += "0";
                str2 += "n";
            }
            epiNE.FormatString = str1;
            epiNE.MaskInput = str2;
            epiNE.NumericType = Infragistics.Win.UltraWinEditors.NumericType.Decimal;
        }

        /// <summary> 初始化EpiNumericEditor数据格式</summary>
        public static void InitEpiDateTimeEditor(EpiDateTimeEditor epiDTE)
        {
            epiDTE.MaskInput = "yyyy/mm/dd";
            epiDTE.FormatString = "yyyy/MM/dd";
        }

        /// <summary> EpiDataView设置columns只读</summary>
        public static void SetEDVReadOnly(EpiDataView edv, string[] columns)
        {
            for (int i = 0; i < columns.Length; i++)
            {
                if (edv.dataView.Table.Columns.Contains(columns[i]))
                {
                    edv.dataView.Table.Columns[columns[i]].ExtendedProperties["ReadOnly"] = true;
                }
            }
        }
        /// <summary> EpiDataView设置columns隐藏</summary>
        public static void SetEDVHidden(EpiDataView edv, string[] columns)
        {
            for (int i = 0; i < columns.Length; i++)
            {
                if (edv.dataView.Table.Columns.Contains(columns[i]))
                {
                    edv.dataView.Table.Columns[columns[i]].ExtendedProperties["IsHidden"] = true;
                }
            }
        }
        /// <summary>发送邮件</summary>
        public static bool SendEmail(string FromAddr, string ReplyToAddr, string ToAddrs, string CCAddrs, string Subject, string Body)
        {
            try
            {
                SmtpClient smtp = new SmtpClient(); //实例化一个SmtpClient
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //将smtp的出站方式设为 Network
                smtp.EnableSsl = false;//smtp服务器是否启用SSL加密
                //smtp.Host = "smtp.nadfinlo.com.cn"; //指定 smtp 服务器地址
                smtp.Host = PubData.SMTP_Host; //"mailx.nadfinlo.com.cn"; //指定 smtp 服务器地址
                smtp.Port = PubData.SMTP_Port;             //指定 smtp 服务器的端口，默认是25，如果采用默认端口，可省去
                //如果你的SMTP服务器不需要身份认证，则使用下面的方式，不过，目前基本没有不需要认证的了
                smtp.UseDefaultCredentials = true;
                //如果需要认证，则用下面的方式
                smtp.Credentials = new NetworkCredential(PubData.SMTP_UserName, PubData.SMTP_Password);
                MailMessage mm = new MailMessage(); //实例化一个邮件类
                mm.Priority = MailPriority.High; //邮件的优先级，分为 Low, Normal, High，通常用 Normal即可
                mm.From = new MailAddress(FromAddr, FromAddr, Encoding.GetEncoding(936));
                mm.ReplyTo = new MailAddress(ReplyToAddr, ReplyToAddr, Encoding.GetEncoding(936));
                mm.To.Add(ToAddrs);
                if (CCAddrs != "")
                {
                    mm.CC.Add(CCAddrs);
                }
                mm.SubjectEncoding = Encoding.GetEncoding(936);
                mm.IsBodyHtml = true; //邮件正文是否是HTML格式
                mm.BodyEncoding = Encoding.GetEncoding(936);
                mm.Subject = Subject;
                String s = Body;
                s = s.Replace("\n", "<br>");
                s = s.Replace(" ", "&nbsp;");
                mm.Body = s;
                //mm.Attachments.Add(new Attachment(@fileName));
                smtp.Send(mm);
                return true;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
                return false;
            }
        }

        /// <summary>隐藏UD界面左边面板</summary>
        public static void HiddenUDLeftPanel(EpiBaseForm form, string[] hiddenControls = null)
        {
            if (hiddenControls == null)
            {
                hiddenControls = new string[] { "dockableWindows3", "_SonomaFormUnpinnedTabAreaLeft" };
            }
            for (int i = 0; i < form.Controls.Count; i++)
            {
                if (Array.IndexOf(hiddenControls, form.Controls[i].Name) >= 0)
                {
                    form.Controls[i].Visible = false;
                }
            }
        }

        /// <summary>隐藏工具栏中新建,删除,保存工具</summary>
        public static void HiddenToolbars(EpiBaseForm form, string[] tools = null)
        {
            if (tools == null)
            {
                tools = new string[] { "NewTool", "NewMenuTool", "DeleteTool", "SaveTool" };
            }
            UltraToolbarsManager BaseToolbarsManager = (UltraToolbarsManager)(form.GetType().InvokeMember("baseToolbarsManager", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance, null, form, null));
            for (var i = 0; i < tools.Length; i++)
            {
                BaseToolbarsManager.Tools[tools[i]].SharedProps.Visible = false;
                BaseToolbarsManager.Tools[tools[i]].SharedProps.Enabled = false;
            }
        }

        /// <summary>绑定DataTable数据到EpiUltraCombo控件</summary>
        public static void LoadDropDown(EpiUltraCombo comControl, DataTable dt, string valueColName, string displayColName)
        {
            string[] columns = new string[dt.Columns.Count];
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                columns[i] = dt.Columns[i].ColumnName;
            }
            comControl.ValueMember = valueColName;
            comControl.DataSource = dt.DefaultView.ToTable(true, columns);
            comControl.DisplayMember = displayColName;
            String[] fields = new String[] { displayColName };
            comControl.SetColumnFilter(fields);
        }

        #endregion

        #region 非常用方法
        /// <summary>登录Epicor </summary>
        public static Session Login(string confPath, string user, string password, string company = "")
        {
            try
            {
                Session _session = new Session(user, password, Session.LicenseType.Default, confPath);

                if (company != "")
                {
                    _session.CompanyID = company; 
                }
                return _session;
            }
            catch (Exception e1)
            {
                throw new Exception("Login Failed!" + e1.Message);
            }
        }

        /// <summary>获取SearchOptions</summary>
        public static SearchOptions GetSearchOptions(string tableName, string whereClause = null)
        {
            Hashtable myHash = new Hashtable();
            myHash.Add(tableName, whereClause);
            return SearchOptions.CreateRuntimeSearch(myHash, DataSetMode.RowsDataSet);
        }
        /// <summary>获取Server名称</summary>
        public static string GetServerName(EpiTransaction otran)
        {
            return ((Session)otran.Session).AppServer.Substring(((Session)otran.Session).AppServer.LastIndexOf('/') + 1);
        }

        /// <summary> 获取数据库连接字符串 </summary>
        public static string GetConnStr(EpiTransaction otran)
        {
            string DBName = PubFun.GetServerName(otran).ToUpper();
            switch (DBName)
            {
                case "DEMO1015":
                    DBName = "DemoDB";
                    break;
                default:
                    throw new Exception("获取数据库名称失败!");

            }
            return String.Format("Initial Catalog={0};Data Source={1};User ID={2};Password={3}", DBName, PubData.DB_IP, PubData.DB_UserID, PubData.DB_Password);
        }

        /// <summary>弹出一个消息框</summary>
        public static void MsgShow(string Value, string title = "", int Width = 300, int Height = 120)
        {
            Form form1 = new Form();
            form1.Size = new Size(Width, Height);
            form1.StartPosition = FormStartPosition.CenterScreen;
            form1.Text = title;
            form1.MaximizeBox = false;
            form1.MinimizeBox = false;
            if (File.Exists(Application.StartupPath + @"\epicor.ico"))
            {
                form1.Icon = new Icon(Application.StartupPath + @"\epicor.ico", 16, 16);
            }
            TextBox tb1 = new TextBox();
            tb1.Multiline = true;
            tb1.ScrollBars = ScrollBars.Vertical;
            tb1.Dock = DockStyle.Fill;
            tb1.Name = "textbox1";
            tb1.Text = Value;
            form1.Controls.Add(tb1);
            form1.ShowDialog();
        }

        public static ViewForm vf = null;
        /// <summary>弹出一个窗口显示数据</summary>
        public static void DebugData(KeyValue[] data, object _this = null)
        {
            if (vf == null || vf.Visible == false)
            {
                vf = new ViewForm();
                vf.Show();
            }
            vf.LoadData(data);
            vf.LoadData2(_this);
        }

        /// <summary>连接共享文件夹</summary>
        public static bool ConnectPath(string path, string userName = "", string passWord = "")
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = @"net use " + path + " /User:" + userName + " " + passWord + " /PERSISTENT:YES";
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }
        /// <summary>从fromDT复制相同列名的数据到toDT</summary>
        public static void CopyTable(DataTable fromDT, DataTable toDT)
        {
            for (int r = 0; r < fromDT.Rows.Count; r++)
            {
                DataRow dr = toDT.NewRow();
                for (int i = 0; i < toDT.Columns.Count; i++)
                {
                    string columnName = toDT.Columns[i].ColumnName;
                    if (fromDT.Columns.Contains(columnName))
                    {
                        dr[columnName] = fromDT.Rows[r][columnName];
                    }
                }
                toDT.Rows.Add(dr);
            }
        }

        ///// <summary>获取服务器文件路径</summary>
        //public static string GetServersPath(string ServerName)
        //{
        //    return @"\\" + PubData.Server_IP + @"\wwwroot\" + ServerName + @"\Server";
        //}
        /// <summary>treeNode加载dt数据</summary>
        public static void LoadTreeNode(TreeNode treeNode, DataTable dt, string pKey)
        {
            DataRow[] drs = dt.Select("pKey='" + pKey + "'");
            for (int i = 0; i < drs.Length; i++)
            {
                TreeNode treeNode1 = new TreeNode()
                {
                    Name = drs[i]["Name"].ToString()
                    ,
                    Text = drs[i]["Text"].ToString()
                    ,
                    Tag = drs[i]
                };
                treeNode.Nodes.Add(treeNode1);
                LoadTreeNode(treeNode1, dt, drs[0]["Key"].ToString());
            }
        }
        #endregion

        #region 反射调用
        /// <summary>给物料新增仓库 </summary>
        public static void NewPartWhse(EpiTransaction otran, string partnum, string warehouse, string binnum = null)
        {
            AdpAssembly adp = new AdpAssembly(otran, "Part");
            try
            {
                adp.BOConnect();
                bool bl = adp.GetByID(new object[] { partnum }, new Type[] { typeof(string) });
                if (bl)
                {
                    DataSet ds1 = adp.GetCurrentDataSet();// (DataSet)adp.InvokeFun("GetCurrentDataSet", new object[] { DataSetMode.RowsDataSet }, new Type[] { typeof(DataSetMode) });
                    string sPlant = ds1.Tables["PartPlant"].Rows[0]["Plant"].ToString();
                    if (ds1.Tables["PartWhse"].Select("WarehouseCode='" + warehouse + "'").Length > 0)
                    {
                        Debug.Print("仓库已经存在!");
                    }
                    else
                    {
                        bool bl1 = (bool)adp.InvokeFun("GetNewPartWhse", new object[] { partnum, sPlant }, new Type[] { typeof(string), typeof(string) });
                        ds1 = adp.GetCurrentDataSet();// (DataSet)adp.InvokeFun("GetCurrentDataSet", new object[] { DataSetMode.RowsDataSet }, new Type[] { typeof(DataSetMode) });
                        if (bl1)
                        {
                            int r = ds1.Tables["PartWhse"].Rows.Count - 1;
                            ds1.Tables["PartWhse"].Rows[r]["WarehouseCode"] = warehouse;
                            if (!string.IsNullOrEmpty(binnum)) ds1.Tables["PartWhse"].Rows[r]["PrimBinNum"] = binnum;
                            adp.Update();
                        }
                    }
                }
            }
            finally
            {
                adp.Dispose();
            }
        }
 



        /// <summary> 调用快速搜索界面 </summary>
        public static object OpenQuickSearchForm(EpiTransaction otrans, string QuickSearchID, bool multiSelect = false, int pageSize = 0, DataTable ControlSetting = null)
        {
            AdpAssembly adp = new AdpAssembly(otrans, "QuickSearch");
            object obj = null;
            try
            {
                adp.BOConnect();
                obj = adp.InvokeFun("ShowQuickSearchForm", new object[] { otrans, QuickSearchID, multiSelect, pageSize, ControlSetting }, new Type[] { typeof(EpiTransaction), typeof(string), typeof(bool), typeof(int), typeof(DataTable) });
            }
            finally
            {
                adp.Dispose();
            }
            return obj;
        }
        #endregion
    }

    /// <summary>自定义列类</summary>
    public class PubColumn
    {
        /// <summary>列名</summary>
        public string ColumnName { get; set; }
        /// <summary>列标题（英文）</summary>
        public string ColumnCaptionEng { get; set; }
        /// <summary>列标题（中文）</summary>
        public string ColumnCaptionSch { get; set; }
        /// <summary>列宽</summary>
        public int ColumnWidth { get; set; }
        /// <summary>数据类型</summary>
        public Type ColumnType { get; set; }
        /// <summary>小数位长度</summary>
        public int ColumnDigits { get; set; }
        /// <summary>允许编辑</summary>
        public Boolean AllowEdit { get; set; }
        /// <summary>是否隐藏</summary>
        public Boolean Hidden { get; set; }
        /// <summary>列描述1</summary>
        public string ColumnDesc1 { get; set; }
        /// <summary>列描述2</summary>
        public string ColumnDesc2 { get; set; }
        /// <summary>列描述3</summary>
        public string ColumnDesc3 { get; set; }
        /// <summary>自定义列构造函数</summary>
        public PubColumn(string _ColumnName, string _ColumnCaptionEng, string _ColumnCaptionSch, int _ColumnWidth = 80, Type _ColumnType = null, int _ColumnDigits = 2, Boolean _AllowEdit = false, Boolean _Hidden = false, string _ColumnDesc1 = "", string _ColumnDesc2 = "", string _ColumnDesc3 = "")
        {
            ColumnName = _ColumnName;
            ColumnCaptionEng = _ColumnCaptionEng;
            ColumnCaptionSch = _ColumnCaptionSch;
            ColumnWidth = _ColumnWidth;
            if (_ColumnType == null)
            {
                ColumnType = typeof(string);
            }
            else
            {
                ColumnType = _ColumnType;
            }
            ColumnDigits = _ColumnDigits;
            AllowEdit = _AllowEdit;
            Hidden = _Hidden;
            ColumnDesc1 = _ColumnDesc1;
            ColumnDesc2 = _ColumnDesc2;
            ColumnDesc3 = _ColumnDesc3;
        }
    }

    /// <summary>BAQ筛选条件</summary>
    public class BAQWhereItem {
        public string Company{ get; set; }
        public string QueryID { get; set; }
        public Guid SubQueryID { get; set; }
        public string TableID { get; set; }
        public Guid CriteriaID { get; set; }
        public int Seq { get; set; }
        public string FieldName { get; set; }
        public string DataType { get; set; }
        public string CompOp { get; set; }
        public string AndOr { get; set; }
        public bool Neg { get; set; }
        public string LeftP { get; set; }
        public string RightP { get; set; }
        public bool IsConst { get; set; }
        public int CriteriaType { get; set; }
        public string ToTableID { get; set; }
        public string ToFieldName { get; set; }
        public string ToDataType { get; set; }
        public string RValue { get; set; }
        public bool ExtSecurity { get; set; }
        public long SysRevID { get; set; }
        public Guid SysRowID { get; set; }
        public int BitFlag { get; set; }
        public string RowMod { get; set; }

        public BAQWhereItem(string tableID, string fieldName, string rValue, string dataType,string andOr = "",string compOp="=", string leftP = "", string rightP = "") {
            TableID = tableID;
            Seq = 0;
            FieldName = fieldName;
            DataType = dataType;
            CompOp = compOp;
            AndOr = andOr;
            Neg = false;
            LeftP = leftP;
            RightP = rightP;
            IsConst = true;
            CriteriaType = 2;
            ToTableID = "";
            ToFieldName = "";
            ToDataType = dataType;
            RValue = rValue;
            ExtSecurity = false;
            BitFlag = 0;
            RowMod = "";
        }
        // public void GetNewQueryWhereItemRow(DataRow row1)
        //{
        //    //DynamicQueryDataSet.QueryWhereItemRow 
        //    // DataRow row1 = dqa.QueryDesignData.QueryWhereItem.NewQueryWhereItemRow();
        //    //DataRow dr = dqa.QueryDesignData.QuerySubQuery.Rows[0];
        //    row1["Company"] = Company;// dr["Company"].ToString();
        //    row1["QueryID"] = QueryID;// dr["QueryID"].ToString();
        //    row1["SubQueryID"] = SubQueryID; //(Guid)dr["SubQueryID"];
        //    row1["TableID"] = TableID;
        //    row1["Seq"] = Seq;
        //    row1["FieldName"] = FieldName;
        //    row1["DataType"] = DataType;
        //    row1["CompOp"] = CompOp;
        //    row1["AndOr"] = AndOr;
        //    row1["Neg"] = Neg;
        //    row1["LeftP"] = LeftP;
        //    row1["RightP"] = RightP;
        //    row1["IsConst"] = IsConst;
        //    row1["CriteriaType"] = CriteriaType;
        //    row1["ToTableID"] = ToTableID;
        //    row1["ToFieldName"] = ToFieldName;
        //    row1["ToDataType"] = ToDataType;
        //    row1["RValue"] = RValue;
        //    row1["ExtSecurity"] = ExtSecurity;
        //    row1["BitFlag"] = BitFlag;
        //    row1["RowMod"] = RowMod;

        //}
        public DynamicQueryDataSet.QueryWhereItemRow GetNewQueryWhereItemRow(DynamicQueryAdapter dqa)
        {
            DynamicQueryDataSet.QueryWhereItemRow row1 = dqa.QueryDesignData.QueryWhereItem.NewQueryWhereItemRow();
            DataRow dr = dqa.QueryDesignData.QuerySubQuery.Rows[0];
            row1.Company = dr["Company"].ToString();
            row1.QueryID = dr["QueryID"].ToString();
            row1.SubQueryID = (Guid)dr["SubQueryID"];
            row1.TableID = TableID;
            row1.Seq = Seq;
            row1.FieldName = FieldName;
            row1.DataType = DataType;
            row1.CompOp = CompOp;
            row1.AndOr = AndOr;
            row1.Neg = Neg;
            row1.LeftP = LeftP;
            row1.RightP = RightP;
            row1.IsConst = IsConst;
            row1.CriteriaType = CriteriaType;
            row1.ToTableID = ToTableID;
            row1.ToFieldName = ToFieldName;
            row1.ToDataType = ToDataType;
            row1.RValue = RValue;
            row1.ExtSecurity = ExtSecurity;
            row1.BitFlag = BitFlag;
            row1.RowMod = RowMod;
            return row1;
        }
    }
}
